<?php

include_once('functions.php');

if(!is_dir($config['IN'])|| !is_dir($config['OUT']) ){
    echo '<p style="color:red">ERROR: some directoriy is not exist or damaged</p>';
    exit;
}
$dir = opendir($config['IN']);
$outputImagesDir = $config['OUT'].'/images';
if(!mkdir($outputImagesDir)){
    if (!file_exists($outputImagesDir)){
        echo 'Error making images directory<br><br>';
        exit;
    }
 };

while($fileName = readdir($dir)){
    if($fileName == '.' || $fileName == '..' || $fileName == 'log.txt')continue;
    $content = file_get_contents($config['IN'].'/'.$fileName, FILE_USE_INCLUDE_PATH);
    preg_match('@(<h2>(.*?)<\/h2>)@', $content, $matches );
    $title = $matches[2];
    preg_match('@(class="highslide" onclick="return hs.expand\(this\)" style="float:left; margin: 10px">([\d|\D]*)<tr><td colspan="2"><hr></td></tr></table>)@', $content, $matches);
    $description = $matches[2];
    
    /* Обработка картинок */
    preg_match('@src="([^\"]*)"@', $description, $matches);
    $remoteImgSrc = $matches[1];
    preg_match('@(.*)\/(.*)\.jpg@' , $remoteImgSrc, $matches);
    $localImageFileName = $matches[2].'.jpg';
    $localImageFilePath = $outputImagesDir.'/'.$localImageFileName;
    $localImageFile = fopen($localImageFilePath, 'wb');
    echo 'Processing image: '.$localImageFileName.'...<br><br>';
    if($localImageFile) $result = curl_get_image($remoteImgSrc);
    else echo 'Error maling image copy <br><br>';
    if($localImageFile) {
        fwrite($localImageFile, $result);
        fclose($localImageFile);
        }
    sleep($config['DELAY']);
    /* Конец обработки картинок */
    
    preg_match('@(&raquo; <a href="/load/knigi_po_filosofii([^\"]*)">(.*)<\/a>)@',$content, $matches);
    $breadcrumbs = $matches[3];
    preg_match( '@(<p style="COLOR: #32cd32;" align="center">([\d|\D]*?)<hr>)@', $content, $matches);
    $links = $matches[2];
    $html = str_replace(array('#breadcrumbs#', '#title#', '#description#', '#links#'), array($breadcrumbs, $title,  $description,  $links),$config['TEMPLATE']);
    $html = str_replace('<p class="MsoNormal"><span lang="BG" style="mso-ansi-language:BG"><o:p>&nbsp;</o:p></span></p></td></tr>','', $html);
    $html = str_replace(array(' class="MsoNormal"', ' style="mso-bidi-font-weight:normal"', '<span lang="BG" style="mso-ansi-language:BG">', '</span>', '<span lang="BG" style="mso-ansi-language:', 'BG"', '</SPAN>', '/go?','</font>'),array('','','','','','','','',''),$html);
    $html = str_replace($remoteImgSrc, 'images/'.$localImageFileName, $html);
    $outputFile = fopen($config['OUT'] .'/'.$fileName, 'w');
    if($outputFile){
        fputs($outputFile, $html  );
        fclose($outputFile);
        echo('Processing file: '.$fileName.'...<br><br>');
    }
}
closedir($dir);

 ?>